package com.tomato.dynamic.threadpool.spring.boot.autoconfigure.support;

import com.tomato.dynamic.threadpool.common.config.DynamicThreadPoolProperties;
import com.tomato.dynamic.threadpool.core.manage.GlobalThreadPoolManage;
import com.tomato.dynamic.threadpool.core.thread.DynamicThreadPoolExecutor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.config.BeanPostProcessor;

/**
 * spring 管理 bean 的后置处理器
 * 线程池注册完成之后注入到spring容器中
 *
 * @author lizhifu
 * @date 2022/4/8
 */
@Slf4j
public class DynamicThreadPoolBeanPostProcessor implements BeanPostProcessor {
    private final DynamicThreadPoolProperties dynamicThreadPoolProperties;

    public DynamicThreadPoolBeanPostProcessor(DynamicThreadPoolProperties dynamicThreadPoolProperties) {
        log.info("DynamicThreadPoolBeanPostProcessor init success {}", dynamicThreadPoolProperties);
        this.dynamicThreadPoolProperties = dynamicThreadPoolProperties;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        if(bean instanceof DynamicThreadPoolExecutor){
            log.info("DynamicThreadPool bean {} init success", beanName);
            DynamicThreadPoolExecutor dynamicExecutor = (DynamicThreadPoolExecutor) bean;
            GlobalThreadPoolManage.registerPool(dynamicExecutor.getThreadPoolName(),dynamicExecutor);
        }
        return bean;
    }
}
